﻿using DotNetty.Buffers;
using DotNetty.Transport.Channels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestNetty.Service.Model;

namespace TestNetty.Client.Handlers
{
    public class ResponseHandler : ChannelHandlerAdapter
    {
        /// <summary>
        /// 消息处理具体的实现
        /// </summary>
        /// <param name="context">可以理解为接收和发送的数据上下文</param>
        /// <param name="message">接收到的服务端发送的内容</param>
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var receiveBuffer = message as MyMessage;
            if (receiveBuffer == null)
            {
                return;
            }
            try
            {
                MyMessage messagesend = new MyMessage();
                switch (receiveBuffer.Id)
                {
                    // 响应给服务端消息
                    case 0:
                        Console.WriteLine($"服务端发来的消息：{receiveBuffer.Content}");
                        messagesend = new MyMessage() { Content = "cs1" , Id = receiveBuffer.Id };
                        context.WriteAndFlushAsync(messagesend);
                        break;
                    case 1:
                        Console.WriteLine($"服务端发来的消息：{receiveBuffer.Content}");
                        messagesend = new MyMessage() { Content = "cs2", Id = receiveBuffer.Id };
                        var receive = context.WriteAndFlushAsync(message);
                        
                        break;
                    default:
                        break;
                }

            }
            catch (Exception)
            {

                throw;
            }
            var myMessage = new MyMessage() { Id = 1 };


            

            
        }

        public override void ChannelActive(IChannelHandlerContext context)
        {
            Console.WriteLine(string.Format("初始化连接时间：{0},{1} 连接成功.", DateTime.Now, context.Name));
            MyMessage request = new MyMessage
            {
                Id = 1001,
                Content = "Hello world."
            };
            context.WriteAndFlushAsync(request);
        }



    }
}
